/**
 * axios二次封装
 */
import axios from 'axios'
import config from '../config'
import { ElMessage }from 'element-plus'
import router from '../router'
import storage from './storage'

// import store from './store' 

const TOKEN_INVALID = 'Token认证失败,请重新登陆!';
const NETWORK_ERROR = '网络请求异常,请稍后重试!';

/**
 * 创建axios实例对象,添加全局配置
 */
const service = axios.create({
    baseURL: config.baseApi,
    timeout:8000
})

// /**
//  * 请求拦截
//  */ 
// request interceptor
service.interceptors.request.use(
    config => {
      // do something before request is sent
    //  console.log(storage.getItem("userInfo"))
    
    var userinfo=storage.getItem("userInfo"); 

    
      if (typeof(userinfo) == "undefined"||userinfo==''||userinfo==null) { 
       
      }else{
       
        config.headers['token'] = userinfo.token 
      }
      return config
    },
    error => {
      // do something with request error
      console.log(error) // for debug
      return Promise.reject(error)
    }
  )
/**
 * 响应拦截
 */
 service.interceptors.response.use((res) => {
     const { code, data, msg } = res.data;
    //  console.log(code,"返回判断")
     if (code === 1) {
        
        return data
     } else if (code === 40001||code === 40003) {
      ElMessage.error(msg);
         setTimeout(() => {
            router.push('login')
         },150)
         return Promise.reject(TOKEN_INVALID)
     }  else if (code ==0) {
      ElMessage.error(msg);
        // return data //TODO:mock数据code有时候为0，也需要数据，所以处理一下，后期换成真实api会删除这里
     } else {
        ElMessage.error(msg || NETWORK_ERROR);
        return Promise.reject(msg || NETWORK_ERROR)
    }
 })

 /**
  * 请求核心函数
  * @param {*} options请求配置
  */
function request(options) {
    options.method = options.method || 'get'
    if (options.method.toLowerCase() === 'get') {
        options.params = options.data
    }
    let isMock = config.mock; //防止我们多人开发的时候，有同事不屑mock:false,这样会导致还是去请求了Mock数据
    if(typeof options.mock != 'undefined'){
        isMock = options.mock;
    }
    console.log(config.env);
    if (config.env == 'production') {
      
    console.log(config);
      service.defaults.baseURL =  config.mockApi
  } else if (config.env === 'prod') {
        service.defaults.baseURL = config.baseApi
    } else {
        service.defaults.baseURL = isMock ? config.mockApi:config.baseApi
    }
    
     return service(options)
}
 
['get', 'post', 'delete', 'patch'].forEach((item) => {
    request[item] = (url, data, options) => {
        return request({
            url,
            data,
            method: item,
            ...options
        })
    }
})

export default request;